package com.sergio.compress.cp.mainUtil;

import com.github.luben.zstd.Zstd;
import com.sergio.compress.cp.base.CompressResult;
import com.sergio.compress.cp.base.CompressTest;
import com.sergio.compress.cp.base.DecompressResult;
import com.sergio.compress.cp.base.TestSource;
import org.springframework.util.StopWatch;

import java.util.Date;

import static com.sergio.compress.cp.base.Const.BUFFER_SIZE;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/14 16:21
 */
public class ZSTD extends CompressTest {

    public int lavel;

    @Override
    public String getType() {
        return "ZSTD_" + lavel;
    }

    public ZSTD() {
        lavel = 3;
    }

    public ZSTD(int level) {
        lavel = level;
    }

    public void setsetDictAttach() {
    }

    public CompressResult compress(byte[] data) {
        //判断byte[]为空
        if (data == null || data.length == 0) {
            return null;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        byte[] compressed = Zstd.compress(data, lavel);
        stopWatch.stop();
        return new CompressResult(getType(), stopWatch.getTotalTimeNanos(), compressed, data.length, compressed.length);
    }

    public DecompressResult decompress(byte[] compressedData, int lengthSource) {
        if (compressedData == null || compressedData.length == 0) {
            return null;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        int size = (int) Zstd.decompressedSize(compressedData);
        byte[] array = new byte[BUFFER_SIZE];
//        byte[] array = new byte[size];
        Zstd.decompress(array, compressedData);

        stopWatch.stop();
        return new DecompressResult(getType(), stopWatch.getTotalTimeNanos(), array, lengthSource, array.length);
    }


    @Override
    public CompressResult compress(TestSource testSource) {
        return compress(testSource.getSourceData());
    }

    @Override
    public DecompressResult decompress(CompressResult testSource) {
        return decompress(testSource.getData(), testSource.getLengthSource());
    }
}
